import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:orginone/components/CommandWidget/index.dart';
import 'package:orginone/components/XScaffold/XScaffold.dart';
import 'package:orginone/dart/base/model.dart';
import 'package:orginone/routers/pages.dart';
import 'package:video_player/video_player.dart';
import '../../../../config/constant.dart';
import '../../../../dart/base/common/commands.dart';

class VideoPlayWidget extends StatefulWidget {
  const VideoPlayWidget({super.key});

  @override
  State<VideoPlayWidget> createState() => _VideoPlayState();
}

class _VideoPlayState extends State<VideoPlayWidget> {
  @override
  void initState() {
    file = RoutePages.routeData.currPageData.data;
    var link = Uri.parse('${Constant.host}${file.shareLink!}');
    videoPlayerController =
        VideoPlayerController.networkUrl(link, httpHeaders: {
      "content-type": "video/mp4",
    });

    Future.delayed(const Duration(seconds: 0), () async {
      await videoPlayerController.initialize();
      chewieController = ChewieController(
          // aspectRatio: 16 / 9,
          videoPlayerController: videoPlayerController,
          autoPlay: true,
          looping: true);
      isInitialized =
          chewieController.videoPlayerController.value.isInitialized;
      if (mounted) {
        command.emitterFlag('play', isInitialized);
      }
      chewieController.addListener(() {
        if (!chewieController.isFullScreen) {
          SystemChrome.setPreferredOrientations(
              [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
        }
      });
    });
    super.initState();
  }

  late FileItemShare file;
  late ChewieController chewieController;
  late VideoPlayerController videoPlayerController;

  var isInitialized = false;

  @override
  Widget build(BuildContext context) {
    return XScaffold(
        titleName: file.name ?? "",
        appBarColor: Colors.black,
        titleStyle: const TextStyle(color: Colors.white),
        backColor: Colors.white,
        backgroundColor: Colors.black,
        body: CommandWidget<bool>(
          flag: 'play',
          builder: (context, data) {
            return !isInitialized
                ? const Center(child: CircularProgressIndicator())
                : Chewie(controller: chewieController);
          },
        ));
  }

  @override
  void dispose() {
    try {
      videoPlayerController.dispose();
      chewieController.dispose();
    } catch (e) {}
    super.dispose();
  }
}
